package com.toommi.refuse.listener;


import com.toommi.refuse.tools.SpringUtil;
import org.springframework.util.CollectionUtils;

import java.util.*;

public class EventUtil {

    public static <Event extends IEvent> void dispatcher(Class<Event> eventClass, Object... objects) {

        try {
            Map<String, Event> eventBeanMap = SpringUtil.getApplicationContext().getBeansOfType(eventClass);
            if (!CollectionUtils.isEmpty(eventBeanMap)) {
                Collection<Event> eventCollection = eventBeanMap.values();
                List<Event> events = new ArrayList<>();
                events.addAll(eventCollection);
                Collections.sort(events, Comparator.comparingInt(IEvent::order));
                for (Event event : events) {
                    event.execute(objects);
                }
            }
        } catch (Exception e) {

        }

    }

}